<template>
  <div class="publicpageview">
    <div class="publicformview">
      <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="区房屋管理单位：" prop="districtId">
              <CompanySelect v-model="listQuery.districtId" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
						<el-form-item label="管理部(分中心)：" prop="houseAdminId">
						  <DeptBrowser v-model="listQuery.houseAdminId" :queryDistrictId="listQuery.districtId" />
						</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="应急抢险时间：" prop="rescueTime">
              <el-date-picker clearable v-model="listQuery.rescueTime" type="date" placeholder="年/月/日"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="应急抢险地址：" prop="rescueAddress">
              <el-input v-model="listQuery.rescueAddress" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="抢险项目：" prop="rescueProject">
              <el-select v-model="listQuery.rescueProject" placeholder="请选择" clearable>
                <el-option v-for="item in dictData.rescueProjectDict" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="抢险人员：" prop="rescuePersonnel">
              <el-input v-model="listQuery.rescuePersonnel" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <div>
              <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
              <el-button size="mini" @click="resetForm('searchForm')">重置</el-button>
            </div>
          </el-col>

        </el-row>


      </el-form>
    </div>

    <div class="publitableview">
      <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
      <el-button type="success" size="mini" @click="handleBatchImport">批量导入</el-button>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row size="mini">
        <el-table-column align="center" label="序号" type="index" width="60">
        </el-table-column>

        <el-table-column align="center" label="区房屋管理单位" prop="houseAdminName" width="160">
        </el-table-column>

        <el-table-column align="center" label="管理部(分中心)" prop="districtName" width="140">
        </el-table-column>

        <el-table-column align="center" label="应急抢险时间" prop="rescueTime" width="180">
          <template slot-scope="scope">
            {{ scope.row.rescueTime }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="应急抢险地址" prop="rescueAddress" width="160">
        </el-table-column>

        <el-table-column align="center" label="抢险项目" prop="rescueProject" width="140">
          <template slot-scope="scope">
            {{ getDictName('rescueProjectDict', scope.row.rescueProject) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="抢险数(处)" prop="rescueCount" width="100">
        </el-table-column>

        <el-table-column align="center" label="抢险人员" prop="rescuePersonnel" width="120">
        </el-table-column>
        <el-table-column align="center" label="备注" prop="note">
        </el-table-column>
        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="handleView(scope.row)">详情</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="publicpaginationview">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" small>
        </el-pagination>
      </div>
    </div>

    <!-- 应急抢救弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" @close="handleDialogClose">
      <el-form :model="formData" :rules="formRules" ref="emergencyForm" label-width="140px" size="small"
        class="safe-form">
        <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="区房屋管理单位：" prop="houseAdminId">
              <CompanySelect v-model="formData.houseAdminId" :display-label.sync="formData.houseAdminName"
                :disabled="isReadonly" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="管理部(分中心)：" prop="districtId">
              <DeptBrowser v-model="formData.districtId" :display-label.sync="formData.districtName"
                :disabled="isReadonly" />
            </el-form-item>
          </el-col>
        </el-row> -->
				<el-row :gutter="20">
					<el-col :span="24">
					  <el-form-item label="区房屋管理单位：" prop="districtId">
					    <CompanySelect v-model="formData.districtId" />
					  </el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="24">
					<el-form-item label="管理部(分中心)：" prop="houseAdminId">
					  <DeptBrowser v-model="formData.houseAdminId" :queryDistrictId="formData.districtId" />
					</el-form-item>
					</el-col>
				</el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="应急抢险时间：" prop="rescueTime">
              <el-date-picker v-model="formData.rescueTime" :disabled="isReadonly" type="datetime"
                placeholder="请选择应急抢险时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="应急抢险地址：" prop="rescueAddress">
              <el-input v-model="formData.rescueAddress" :disabled="isReadonly" placeholder="请输入应急抢险地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="抢险项目：" prop="rescueProject">
              <el-select v-model="formData.rescueProject" :disabled="isReadonly" placeholder="请选择抢险项目"
                style="width: 100%">
                <el-option v-for="item in dictData.rescueProjectDict" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="抢险数(处)：" prop="rescueCount">
              <el-input-number v-model="formData.rescueCount" :disabled="isReadonly" :min="1" :max="999"
                placeholder="请输入抢险数量" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="抢险人员：" prop="rescuePersonnel">
              <el-input v-model="formData.rescuePersonnel" :disabled="isReadonly" placeholder="请输入抢险人员姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注：" prop="note">
              <el-input v-model="formData.note" :disabled="isReadonly" type="textarea" :rows="3"
                placeholder="请输入备注信息"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!isReadonly" type="primary" @click="handleConfirm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入弹窗 -->
    <el-dialog title="上传文件" :visible.sync="uploadDialogVisible" width="900px" @close="handleUploadDialogClose">
      <div class="upload-container">
        <el-upload class="upload-dragger" drag :action="uploadAction" :file-list="fileList"
          :on-success="handleUploadSuccess" :on-error="handleUploadError" :on-change="handleFileChange"
          :before-upload="beforeUpload" :auto-upload="false" accept=".xls,.xlsx" ref="upload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            请将文件拖动到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            只能上传 .xls/.xlsx 文件，且不超过 10MB
          </div>
        </el-upload>
        <div class="template-download">
          下载模板：<el-button type="text" @click="downloadTemplate">应急抢险模板</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleImport" :loading="importLoading">导 入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRescueList, addRescue, updateRescue, deleteRescue } from '@/api/safe/yingjiqiangxian'
import { formatDate, formatDateTime } from '@/utils/dateUtils'
import { convertObjectIntegersToStrings } from '@/utils/dataUtils'
import CompanySelect from "@/components/commonSelect/companySelect.vue"
import DeptBrowser from "@/components/SysBrowser/DeptBrowser.vue"

export default {
  name: 'YingjiQiangjiu',
  components: { CompanySelect, DeptBrowser },

  data() {
    return {
      // 字典数据
      dictData: {
        // 抢险项目字典
        rescueProjectDict: [
          { id: '1', name: '房屋结构加固' },
          { id: '2', name: '屋面防水处理' },
          { id: '3', name: '墙体裂缝修复' },
          { id: '4', name: '地基沉降处理' },
          { id: '5', name: '安全围挡设置' },
          { id: '6', name: '临时支撑搭建' }
        ]
      },
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        houseAdminId: "",
        districtId: "",
        rescueTime: "",
        rescueAddress: "",
        rescueProject: "",
        rescuePersonnel: ""
      },
      total: 0,
      list: [],
      listLoading: false,
      dialogVisible: false,
      uploadDialogVisible: false,
      isReadonly: false,
      submitLoading: false,
      importLoading: false,
      dialogTitle: '',
      uploadAction: '',
      fileList: [],
      formData: {
        id: null,
        houseAdminId: '',
        houseAdminName: '',
        districtId: '',
        districtName: '',
        rescueTime: '',
        rescueAddress: '',
        rescueProject: '',
        rescueCount: 1,
        rescuePersonnel: '',
        note: ''
      },
      currentEditId: null,
      formRules: {
        houseAdminId: [
          { required: true, message: '请选择区房屋管理单位', trigger: 'change' }
        ],
        districtId: [
          { required: true, message: '请选择管理部', trigger: 'change' }
        ],
        rescueTime: [
          { required: true, message: '请选择应急抢险时间', trigger: 'change' }
        ],
        rescueAddress: [
          { required: true, message: '请输入应急抢险地址', trigger: 'blur' }
        ],
        rescueProject: [
          { required: true, message: '请选择抢险项目', trigger: 'change' }
        ],
        rescueCount: [
          { required: true, message: '请输入抢险数量', trigger: 'blur' }
        ],
        rescuePersonnel: [
          { required: true, message: '请输入抢险人员', trigger: 'blur' }
        ]
      }
    };
  },

  mounted() {
    this.getList();
  },

  methods: {
    // 通用字典名称查找方法
    getDictName(dictType, id) {
      const item = this.dictData[dictType].find(item => item.id == String(id));
      return item ? item.name : id;
    },

    // 格式化日期 - 使用工具类方法
    formatDate,
    // 分页大小改变
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    // 获取列表数据
    getList() {
      this.listLoading = true;

      // 构建请求参数，过滤空值
      const params = {};
      Object.keys(this.listQuery).forEach(key => {
        if (this.listQuery[key] !== '') {
          params[key] = this.listQuery[key];
        }
      });

      // 调用应急抢险分页接口
      getRescueList(params)
        .then(response => {
          this.listLoading = false;
          if (response.code == 200) {
            // 使用数据转换工具处理整数转字符串
            this.list = convertObjectIntegersToStrings(response.data.list || []);
            this.total = response.data.total || 0;
          } else {
            this.$message.error(response.message || '获取数据失败');
          }
        })
        .catch(error => {
          this.listLoading = false;
          console.error('获取应急抢险数据失败:', error);
          this.$message.error('获取数据失败，请检查网络连接');
        });
    },

    // 搜索
    handleSearch() {
      this.listQuery.pageNum = 1;
      this.getList();
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getList();
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增应急抢险';
      this.isReadonly = false;
      this.currentEditId = null;
      this.resetFormData();
      this.dialogVisible = true;
    },

    // 重置表单数据
    resetFormData() {
      this.formData = {
        id: null,
        houseAdminId: '',
        houseAdminName: '',
        districtId: '',
        districtName: '',
        rescueTime: '',
        rescueAddress: '',
        rescueProject: '',
        rescueCount: 1,
        rescuePersonnel: '',
        note: ''
      };
    },

    // 修改
    handleUpdate(row) {
      this.dialogTitle = '修改应急抢险';
      this.isReadonly = false;
      this.currentEditId = row.id;

      // 直接使用表格行数据，不发送后台请求
      this.formData = convertObjectIntegersToStrings(row) || {};
      this.dialogVisible = true;
    },



    // 详情
    handleView(row) {
      this.dialogTitle = '应急抢险详情';
      this.isReadonly = true;
      this.currentEditId = row.id;

      // 直接使用表格行数据，不发送后台请求
      this.formData = convertObjectIntegersToStrings(row) || {};
      this.dialogVisible = true;
    },

    // 删除
    handleDelete(id) {
      this.$confirm('此操作将删除该条内容，请确认是否继续操作？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        deleteRescue(id)
          .then(response => {
            if (response.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList(); // 刷新列表
            } else {
              this.$message.error(response.message || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除应急抢险失败:', error);
            this.$message.error('删除失败，请检查网络连接');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 弹窗关闭
    handleDialogClose() {
      this.resetFormData();
      this.$refs.emergencyForm.resetFields();
    },

    // 确认提交
    handleConfirm() {
      this.$refs.emergencyForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;

          // 准备提交数据，新增时不传id
          const submitData = { ...this.formData };
          if (!this.currentEditId) {
            delete submitData.id;
          }

          // 根据是否有ID决定使用新增还是修改接口
          const apiCall = this.currentEditId ? updateRescue(submitData) : addRescue(submitData);

          apiCall
            .then(response => {
              this.submitLoading = false;
              if (response.code == 200) {
                this.dialogVisible = false;
                const action = this.currentEditId ? '修改' : '新增';
                this.$message.success(`${action}成功！`);
                this.getList(); // 刷新列表
              } else {
                this.$message.error(response.message || '操作失败');
              }
            })
            .catch(error => {
              this.submitLoading = false;
              console.error('保存应急抢险失败:', error);
              this.$message.error('操作失败，请检查网络连接');
            });
        }
      });
    },

    // 批量导入
    handleBatchImport() {
      this.uploadDialogVisible = true;
      this.fileList = [];
    },

    // 上传弹窗关闭
    handleUploadDialogClose() {
      this.fileList = [];
      this.$refs.upload.clearFiles();
    },

    // 文件上传前校验
    beforeUpload(file) {
      const isExcel = file.type == 'application/vnd.ms-excel' || file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },

    // 文件变化
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },

    // 上传成功
    handleUploadSuccess(response, file, fileList) {
      this.$message.success('文件上传成功');
    },

    // 上传失败
    handleUploadError(error, file, fileList) {
      this.$message.error('文件上传失败');
    },

    // 执行导入
    handleImport() {
      if (this.fileList.length == 0) {
        this.$message.warning('请先选择要上传的文件');
        return;
      }

      this.importLoading = true;
      setTimeout(() => {
        this.importLoading = false;
        this.uploadDialogVisible = false;
        this.$message.success('导入成功');
        this.getList();
      }, 2000);
    },

    // 下载模板
    downloadTemplate() {
      this.$message.success('模板下载中...');
    }
  }
};
</script>

<style scoped>
.upload-container {
  padding: 20px 0;
  width: 100%;
}

.upload-dragger {
  width: 100% !important;
}

.upload-dragger .el-upload {
  width: 100% !important;
}

.upload-dragger .el-upload-dragger {
  width: 100% !important;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s ease;
  background-color: #fafafa;
  box-sizing: border-box;
}

.upload-dragger .el-upload-dragger:hover {
  border-color: #409EFF;
  width: 100%;
}

.upload-dragger .el-upload-dragger .el-icon-upload {
  font-size: 67px;
  color: #C0C4CC;
  margin: 40px 0 16px;
  line-height: 50px;
  width: 100%;
}

.upload-dragger .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-dragger .el-upload__text em {
  color: #409EFF;
  font-style: normal;
}

.template-download {
  margin-top: 20px;
  text-align: center;
}

::v-deep .el-upload {
  width: 100% !important;
}

::v-deep .el-upload-dragger {
  width: 100% !important;
}
</style>